# 编写订单表相关业务
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response

from apps.meiduo_admin.serializers.orders import OrderInfoSerialzier
from apps.orders.models import OrderInfo
from apps.meiduo_admin.utils import NumPage


class OrdersView(ModelViewSet):
    # 指定序列化器
    serializer_class = OrderInfoSerialzier
    # 指定查询集
    queryset = OrderInfo.objects.all()
    # 指定权限
    permission_classes = [IsAdminUser]
    # 指定分页
    pagination_class = NumPage

    # 重写GenericAPIView类中的获取数据方法get_queryset
    def get_queryset(self):
        # 获取关键字keyword   keyword是查询字符串数据  request.query_params 获取查询字符串数据
        keyword = self.request.query_params.get('keyword')
        # 根据关键返回不同的数据内容
        if keyword == '' or keyword == None:
            return self.queryset
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)  # contains 是否包含

    @action(methods=['put'], detail=True)  # /orders/(?P<pk>\d+)/status/
    def status(self, request, pk):
        # 根据获取的order_id查询订单是否存在
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error': '订单不存在'}, status=400)
        # 获取订单状态数据
        status = request.data.get('status')
        # 修改订单状态
        order.status = status
        order.save()
        return Response({'order_id': order.order_id, 'status': status})
